const express = require('express')
const router = express.Router()
const webInfoModel = require('./../model/webInfoModel')
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads')
  },
  filename: function(req, file, cb) {
    cb(null, `${Date.now()}-${file.originalname}`)
  }
})
const upload = multer({ storage: storage })

// 新增
router.post('/api/webInfo', async (req, res) => {
  let carouseInfo = req.body
  let files = req.files
  let data = {
    msg: '新增失败',
    code: 0,
    data: false
  }
  if (files[0]) {
    carouseInfo['picture'] = files[0].filename
  }
  const carouseCreate = await carouselModel.create(carouseInfo)
  if (carouseCreate) {
    data.code = 1
    data.msg = '新增成功'
    data.data = carouseCreate
  }

  res.send(data)
})
// 修改
router.put('/api/webInfo', upload.array('picture', 40), async (req, res) => {
  let carouseInfo = req.body
  let files = req.files
  if (files[0]) {
    carouseInfo['picture'] = files[0].filename
  }
  let data = {
    msg: '修改失败',
    code: 0,
    data: false
  }
  const carouseJuge = await carouselModel.findOne({
    _id: carouseInfo.id
  })
  if (carouseJuge) {
    const carouseUpdate = await carouselModel.update(carouseInfo)
    if (carouseUpdate) {
      data.code = 1
      data.msg = '修改成功'
      data.data = true
    } else {
      data.msg = '修改失败'
    }
  } else {
    data.msg = '轮播图Id不存在'
  }
  res.send(data)
})
// 删除
router.delete('/api/webInfo', upload.array('picture', 40), async (req, res) => {
  let carouseInfo = req.body
  let data = {
    msg: '删除失败',
    code: 0,
    data: false
  }
  if (carouseInfo.id) {
    const idArr = carouseInfo.id.split(',')
    console.log(idArr)
    const carouseDelete = await carouselModel.remove({
      _id: { $in: idArr }
    })
    if (carouseDelete) {
      data.code = 1
      data.msg = '删除成功'
      data.data = true
    } else {
      data.msg = '删除失败'
    }
  } else {
    data.msg = '轮播图Id不存在'
  }
  res.send(data)
})
// 获取
router.get('/api/webInfo', upload.array('picture', 40), async (req, res) => {
  let carouseInfo = req.query
  let data = {
    msg: '查询失败',
    code: 0,
    data: false
  }
  const page = Number(carouseInfo.page)
  const size = Number(carouseInfo.size)
  if (size) {
    const carouseGet = await carouselModel
      .find({})
      .skip(page * size)
      .limit(size)
      .sort({ _id: '-1' })
    if (carouseGet) {
      data.code = 1
      data.msg = '查询成功'
      data.data = carouseGet
    } else {
      data.msg = '删除失败'
    }
  } else {
    data.msg = '查询参数失败'
  }
  res.send(data)
})
module.exports = router
